﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;

namespace EzFrameWork
{
    [Serializable]
    public class Hert
    {
        public string ID;
        public DateTime Time;
    }

    public enum MessageType
    {
        HERTPACK = 0,//心跳包
        FILE = 1,//文件 可以是任何类型
        JSON = 2,//Json 类型的数据包
        SENDID = 3,//用与服务器分配ID
        TEXT = 4,
        BYE = 5,//主动告诉服务器我下线了
    }
    //对将要发送的消息进行封装
    public class MessageAgreement
    {
        //对数据封包 只是在数据头中添加了长度 和 消息码
        public static byte[] WriteSimpleDataPack(string data, MessageType messageType)
        {
            byte[] dataBytes = Encoding.UTF8.GetBytes(data);
            byte[] messageTypeByte = BitConverter.GetBytes((int)messageType);
            int dataLangth = dataBytes.Length + messageTypeByte.Length;
            byte[] lengthBytes = BitConverter.GetBytes(dataLangth);
            byte[] newBytes = lengthBytes.Concat(messageTypeByte).ToArray().Concat(dataBytes).ToArray();
            return newBytes;
        }

        public static byte[] WriteSimpleDataPack(byte[] data, MessageType messageType)
        {
            byte[] dataBytes = data;
            byte[] messageTypeByte = BitConverter.GetBytes((int)messageType);
            int dataLangth = dataBytes.Length + messageTypeByte.Length;
            byte[] lengthBytes = BitConverter.GetBytes(dataLangth);
            byte[] newBytes = lengthBytes.Concat(messageTypeByte).ToArray().Concat(dataBytes).ToArray();
            return newBytes;
        }

        //解析数据
        public static void ReadSimpleDataPack(byte[] data, Action<MessageType, byte[]> action)
        {
            MessageType type = (MessageType)BitConverter.ToInt32(data, 0);
            byte[] Realdata = data.Skip(4).ToArray();
            action(type, Realdata);
        }

        //用于解析心跳包
        public static string ReadHertGetID(byte[] data)
        {
            string datatemp = Encoding.UTF8.GetString(data);
            Hert hert = JsonUtility.FromJson<Hert>(datatemp);
            if (hert.ID != null)
            {
                return hert.ID;
            }
            return null;
        }
    }
}

